import cv2
import numpy as np
from PIL import Image


def check_colors_similar(image, locs, colors, tolerance=10):
    for loc in locs:
        for rgb_color in colors:
            pixel_color = image.getpixel(loc)
            flag = all(abs(c1 - c2) <= tolerance for c1, c2 in zip(pixel_color, rgb_color))
            # print(f"loc: {loc}, pixel_color: {pixel_color}, rgb_color:{rgb_color}, flag:{flag}")
            if flag:
                return True
    return False


def find_coordinates(image, left_top, right_down, rgb_color, one=False, tolerance=10):
    coordinates = []

    target_color = rgb_color[:3]  # 忽略透明度

    if left_top[0] > image.width or right_down[0] > image.width:
        raise ValueError("x is out of image.width")
    if left_top[1] > image.height or right_down[1] > image.height:
        raise ValueError("y is out of image.height")

    for x in range(left_top[0], right_down[0]):
        for y in range(left_top[1], right_down[1]):
            pixel_color = image.getpixel((x, y))[:3]  # 忽略透明度
            if all(abs(pixel_color[i] - target_color[i]) <= tolerance for i in range(3)):
                coordinates.append((x, y))
                if one:
                    break
    return coordinates


def find_one_coordinate(image, left_top, right_down, rgb_color):
    coordinates = find_coordinates(image, left_top, right_down, rgb_color, one=True)
    if len(coordinates) > 0:
        return True, coordinates[0]
    else:
        return False, None


def cv2pil(img_cv):
    return Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB))


def pil2cv(img_pil):
    return cv2.cvtColor(np.asarray(img_pil), cv2.COLOR_RGB2BGR)
